package com.lwj.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lwj.dao.MerchantMapper;
import com.lwj.dao.UserMapper;
import com.lwj.entity.Merchant;
import com.lwj.entity.User;
import com.lwj.service.UserService;
import com.lwj.util.DataRet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by LWJ on 2018/4/26.
 */

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MerchantMapper merchantMapper;

    @Override
    public DataRet<User> getUser(User u,HttpSession session,int role) {
        if (role==1){
            User user=userMapper.selectByUser(u);
            if (user==null){
                return new DataRet<>(null);
            }else {
                session.setAttribute("user",user);
                return new DataRet<>(user);
            }
        }else{
            Merchant merchant= merchantMapper.findByNameAndPassword(u);
            if (merchant==null){
                return new DataRet<>(null);
            }else {
                session.setAttribute("merchant",merchant);
                User user=new User();
                user.setId(merchant.getId());
                user.setUsername(merchant.getAddress());
                return new DataRet<>(user);
            }
        }

    }

    @Override
    public DataRet<User> getUserByUserName(String userName) {
        User u=new User();
        u.setUsername(userName);
        return new DataRet<>(userMapper.selectByUser(u));
    }

    @Override
    public PageInfo<User> searchUser(String userName,int pageNo,int pageSize) {
        if("null".equals(userName)){
            userName="";
        }
        User u=new User();
        u.setUsername(userName);
        PageHelper.startPage(pageNo, pageSize);
        PageInfo<User> pageInfo= new PageInfo<>(userMapper.searchUser(u));
        return pageInfo;
    }

    @Override
    public PageInfo<User> getUserByType(int pageNo, int pageSize, int typeId) {
        PageHelper.startPage(pageNo, pageSize);
        return new PageInfo<>(userMapper.searchUserByType(typeId));
    }
}
